package com.chat.common.user.service.impl;

import com.chat.common.common.annotation.RedissonLock;
import com.chat.common.common.service.LockService;
import com.chat.common.user.dao.UserBackpackDao;
import com.chat.common.user.domain.entity.UserBackpack;
import com.chat.common.user.domain.enums.IdempotentEnum;
import com.chat.common.user.service.IUserBackpackService;
import com.chat.common.user.service.adapter.UserBackpackAdapter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class IUserBackpackServiceImpl implements IUserBackpackService {
    @Resource
    private UserBackpackDao userBackpackDao;

    @Resource
    @Lazy
    private IUserBackpackServiceImpl userBackpackService;

    @Override
    public void acquireItem(Long uid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        String idempotent = getIdempotent(itemId, idempotentEnum, businessId);
        userBackpackService.doAcquireItem(uid, itemId, idempotent);

    }

    @RedissonLock(key = "#idempotent", waitTime = 5000)//相同幂等如果同时发奖，需要排队等上一个执行完，取出之前数据返回
    public void doAcquireItem(Long uid, Long itemId, String idempotent) {
        UserBackpack byIdempotent = userBackpackDao.getByIdempotent(idempotent);
        //如果幂等 纯在说明 物品已经发放 无需再次发放
        if(Objects.nonNull(byIdempotent)){
            return;
        }
        //发放 勋章
        UserBackpack userBackpack = UserBackpackAdapter.buildBackpack(uid, itemId, idempotent);
        userBackpackDao.save(userBackpack);
    }


    private String getIdempotent(Long itemId, IdempotentEnum idempotentEnum, String businessId) {
       return String.format("%d_%d_%s", itemId, idempotentEnum.getType(), businessId);
    }
}
